import re

import pdfplumber
from flask import jsonify


# def extract_table_from_pdf(pdf_path):
    # info1 = {"类型": "发票"}
    # try:
    #     with pdfplumber.open(pdf_path) as pdf:
    #         page = pdf.pages[0]  # 假设表格在第一页
    #         tables = page.extract_tables()
    #         text = page.extract_text()
    #         if tables and len(tables) > 0:
    #             main_table = extract_main_table(tables)
    #             if main_table:
    #                 extract_info_from_table(main_table, info1)
    #             else:
    #                 return jsonify({"error": str("找不到主表格！")}), 200
    #         # else:
    #         #     return jsonify({"error":str("找不到主表格！")}),200
    #         if text and len(text) > 0:
    #             lines = text.split("\n")
    #             title = False
    #             for line in lines:
    #                 if len(info1) >= 7:
    #                     break
    #                 if not title and line.__contains__("发票"):
    #                     title = True
    #                     info1["发票名称"] = line
    #                 elif line.__contains__("号码"):
    #                     line = line.replace(":", "：")
    #                     info1["发票号码"] = line.split("：")[1].replace(" ", "")
    #                 elif line.__contains__("开票日期"):
    #                     line = line.replace(":", "：")
    #                     info1["开票日期"] = line.split("：")[1].replace(" ", "")
    #                 else:
    #                     continue
    # except FileNotFoundError:
    #     print(f"错误: 文件 {pdf_path} 未找到。")
    #     return jsonify({"error": str("文件" + pdf_path + "未找到！")}), 200
    # except Exception as e:
    #     print(f"错误: 发生未知错误 {e}。")
    #     return jsonify({"error": str("发生未知错误！" + e)}), 200
    # if info1.get("开票日期") is None or info1.get("开票日期") == "":
    #     date_pattern = r"([\d]{4}年[\d]{1,2}月[\d]{1,2}日)"
    #     match = re.search(date_pattern, text)
    #     info1["开票日期"] = match.group(1) if match else None
    # if info1.get("发票号码") is None or info1.get("发票号码") == "":
    #     date_pattern = r"([\d]{20})"
    #     match = re.search(date_pattern, text)
    #     info1["发票号码"] = match.group(1) if match else None
    # return str(info1)

def extract_table_from_pdf(pdf_path):
    info1 = {"类型": "发票"}  
    try:
        with pdfplumber.open(pdf_path) as pdf:
            # 检查PDF是否有页面
            if not pdf.pages:
                return jsonify({"error": "PDF文件无内容页"}), 200
            
            page = pdf.pages[0]  # 取第一页
            tables = page.extract_tables()
            text = page.extract_text() or ""  # 确保text不为None
            
            # 1. 尝试从表格提取
            if tables and len(tables) > 0:
                main_table = extract_main_table(tables)  # 假设已有此函数
                if main_table:
                    extract_info_from_table(main_table, info1)  # 假设已有此函数
            
            # 2. 从文本行提取（无论是否有表格，都做补充提取）
            if text.strip():  # 文本非空
                lines = text.split("\n")
                title_found = False  # 避免重复提取发票名称
                
                for line in lines:
                    line = line.strip()  # 去除首尾空格
                    if not line:
                        continue  # 跳过空行
                    
                    # 提取发票名称（包含"发票"且未提取过）
                    if not title_found and "发票" in line:
                        info1["发票名称"] = line
                        title_found = True
                    
                    # 提取发票号码（包含"号码"关键词）
                    if "发票号码" in line or "号码" in line:
                        line = line.replace(":", "：")  # 统一冒号格式
                        parts = line.split("：")
                        if len(parts) >= 2:
                            info1["发票号码"] = parts[1].replace(" ", "")  # 去空格
                    
                    # 提取开票日期（包含"开票日期"关键词）
                    if "开票日期" in line:
                        line = line.replace(":", "：")
                        parts = line.split("：")
                        if len(parts) >= 2:
                            info1["开票日期"] = parts[1].replace(" ", "")
            
            # 3. 正则兜底（如果上述步骤未提取到）
            # 补充开票日期
            if not info1.get("开票日期"):
                date_pattern = r"(\d{4}年\d{1,2}月\d{1,2}日)"
                match = re.search(date_pattern, text)
                if match:
                    info1["开票日期"] = match.group(1)
            
            # 补充发票号码（20位数字，可根据实际调整位数）
            if not info1.get("发票号码"):
                num_pattern = r"(\d{20})"
                match = re.search(num_pattern, text)
                if match:
                    info1["发票号码"] = match.group(1)
            
            # 补充价税合计
            if not info1.get("价税合计"):
                # 模式1：匹配“价税合计”关键词后的金额
                price_pattern = r"价税合计.*?[：:]\s*([￥¥]\d+\.\d+)"
                match = re.search(price_pattern, text, re.IGNORECASE)
                if match:
                    info1["价税合计"] = str(match.group(1)).replace(" ", "")
                else:
                    # 模式2：匹配最后一个带￥/¥的金额
                    price_pattern_backup = r"([￥¥]\d+\.\d+)\s*$"
                    matches = re.findall(price_pattern_backup, text, re.MULTILINE)
                    if matches:
                        info1["价税合计"] = str(matches[-1])
                    else:
                        # 模式3：匹配带“元”的纯数字金额
                        price_pattern_fallback = r"(\d+\.\d+)\s*元"
                        match = re.search(price_pattern_fallback, text)
                        if match:
                            info1["价税合计"] = f"￥{match.group(1)}"
    
    except FileNotFoundError:
        error_msg = f"文件 {pdf_path} 未找到"
        print(f"错误: {error_msg}")
        return jsonify({"error": error_msg}), 404  # 建议用404状态码
    
    except Exception as e:
        error_msg = f"处理失败: {str(e)}"
        print(f"错误: {error_msg}")
        return jsonify({"error": error_msg}), 500  # 服务器错误用500
    
    # 最终返回字典（而非字符串），方便前端解析
    return str(info1)



def extract_main_table(table):
    for main_table in table:
        for row in main_table:
            for r in row:
                charact = str(r.replace("\n", ""))
                if "购买方" in charact:
                    return main_table
    return table[0]


def extract_info_from_table(main_table, info1):
    if main_table:
        info = main_table[0]
        str0 = str(info[0])
        str0 = str0.replace("\n", "")
        info[1] = info[1].replace(":", "：")
        str_list = info[1].split("\n")
        if str0.__contains__("购买方"):
            info1["购买方名称"] = str_list[0].split("：")[1]
            info1["购买方纳税人编号"] = str_list[1].split("：")[1]
        # 提取小写的价税合计
        for row in main_table:
            for cell in row:
                if cell and "（小写）" in str(cell):
                    total_amount_str = str(cell).split("（小写）")[1].replace("¥", "")
                    info1["价税合计"] = total_amount_str
                    break
